package com.hopedove.callsystem.activity

import android.content.Context
import android.content.Intent
import android.os.Bundle
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.hopedove.base.BaseActivity
import com.hopedove.callsystem.activity.MaopiCheck.SCQCallActivity
import com.hopedove.callsystem.activity.call.BackTrayCallActivity
import com.hopedove.callsystem.activity.call.MaterialInfoActivity
import com.hopedove.callsystem.activity.call.ScanBarcodeActivity
import com.hopedove.callsystem.constant.TICKET_NO
import com.hopedove.callsystem.databinding.ActivityCheckLayoutBinding
import com.hopedove.callsystem.domain.net.CheckClothNo
import com.hopedove.callsystem.domain.net.CheckWhloc
import com.hopedove.callsystem.domain.net.GetMaterialInfo
import com.hopedove.net.ErrResponse
import com.hopedove.net.OkResponse
import com.hopedove.net.domain.Communication
import com.hopedove.utils.ToastUtil
import com.hopedove.view.SimpleDialog
import com.hoperun.callsystem.entity.CarEntity
import org.json.JSONArray
import org.json.JSONObject
import java.io.Serializable

class ScanCheckActivity : BaseActivity() {

    private var mType = -1

    companion object {
        fun actionStart(context: Context, type: Int?) {
            val intent = Intent(context, ScanCheckActivity::class.java)
            intent.putExtra("type", type)
            context.startActivity(intent)
        }

        //  生产区呼叫
        const val TYPE_SHENGCHAN_CALL = 0
        const val TYPE_YUANLIAO_CALL = 1
    }

    lateinit var binding: ActivityCheckLayoutBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityCheckLayoutBinding.inflate(layoutInflater)
        setContentView(binding.root)
        initViewAndEvent()
    }

    private fun initViewAndEvent() {
        mType = this.intent.getIntExtra("type", -1)

        binding.okBtn.setOnClickListener {
            startCheck()
        }
    }


    private fun startCheck() {

        val clothTktNo = binding.inputEt.text.toString().trim()
        if (clothTktNo.isEmpty()) {
            SimpleDialog.show(this, "请输入条码后再确认！")
            return
        }
        when (mType) {
            0 -> checkClothNo()
            1 -> getMaterialInfo()
        }
    }


    private fun checkClothNo() {
        val clothTktNo = binding.inputEt.text.toString().trim()
        if (clothTktNo.isEmpty()) {
            SimpleDialog.show(this, "请输入条码后再确认！")
            return
        }
        showWait()
        Communication.asyncRequest(CheckClothNo(clothTktNo)) { r ->
            stopWait()

            when (r) {
                is OkResponse -> {
                    try {
                        val clothTktNo = binding.inputEt.text.toString().trim()
                        Intent(this, SCQCallActivity::class.java).apply {
                            putExtra("clothtktNo", clothTktNo)
                            startActivity(this)
                        }
                        //需要对输入框清空
                        binding.inputEt.setText("")

                    } catch (e: Exception) {
                        ToastUtil.longToast(this, e.toString())
                    }
                }

                is ErrResponse -> {
                    SimpleDialog.show(this, "检验呼叫失败！")
                }
            }

        }
    }

    private fun checkWhlo() {
        val clothTktNo = binding.inputEt.text.toString().trim()
        if (clothTktNo.isEmpty()) {
            SimpleDialog.show(this, "请输入条码后再确认！")
            return
        }
        showWait()
        Communication.asyncRequest(CheckWhloc(clothTktNo)) { r ->
            stopWait()
            if (r is OkResponse) {
                val jsonObj = JSONObject(r.data)
                val msg = jsonObj.optString("MSG_INFO")
                val OPT_REMARK = jsonObj.optString("OPT_REMARK")
                //0是不用弹出退托盘画面，1是弹出退托盘画面且必须退一个托盘才能继续呼叫
                if (OPT_REMARK == "0") {
                    goRawMaterial()
                } else if (OPT_REMARK == "1") {
                    var data = jsonObj.optJSONArray("DATALIST")
                    val carList = Gson().fromJson<List<CarEntity>>(
                        data.toString(),
                        object : TypeToken<List<CarEntity>>() {}.type
                    )
                    val clothTktNo = binding.inputEt.text.toString().trim()
                    SimpleDialog.show(this, msg,
                        SimpleDialog.OnPositiveClickListener {
                            val intent = Intent(this, BackTrayCallActivity::class.java)
                            intent.putExtra("dataList", carList as Serializable)
                            intent.putExtra("clothTktNo", clothTktNo)
                            intent.putExtra("materiaInfo", materialInfo)
                            startActivityForResult(intent, 1)
                        })
                }

            } else if (r is ErrResponse) {
                SimpleDialog.show(this, "检验呼叫失败！")
            }
        }
    }

    /**
     * 获取原料信息
     */
    private fun getMaterialInfo() {
        val clothTktNo = binding.inputEt.text.toString().trim()
        if (clothTktNo.isEmpty()) {
            SimpleDialog.show(this, "请输入条码后再确认！")
            return
        }
        showWait()

        Communication.asyncRequest(GetMaterialInfo(clothTktNo)) { r ->
            stopWait()
            if (r is OkResponse) {
                val jsonArray = JSONArray(r.data)
                //通过时 ，再去校验三联号
                materialInfo = r.data//存储返回信息
                checkWhlo()

            } else if (r is ErrResponse) {
                SimpleDialog.show(this, r.errText)
            }
        }
    }


    var materialInfo = ""
    private fun goRawMaterial() {
        val intent = Intent(this@ScanCheckActivity, MaterialInfoActivity::class.java)
        intent.putExtra(TICKET_NO, binding.inputEt.text.toString())
        intent.putExtra(ScanBarcodeActivity.SOURCE_DATA, materialInfo)
        startActivity(intent)
    }


}